package com.example.day04_fragment;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {

    private TextView tv;
    private RadioGroup rg;
    private RadioButton rb1;
    private RadioButton rb2;
    private FrameLayout frameOne;

    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("sss", "onCreateView: 创建布局");
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        initView(view);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //给ThreeFragment的tv发送值
                Message message = new Message();
                message.what = 200;
                message.obj = "张三";
                ThreeFragment.handler.sendMessage(message);
            }
        });
        //给twofragment发送值
        tv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                TwoFragment twoFragment = (TwoFragment) getActivity().getSupportFragmentManager().findFragmentByTag("two");
                twoFragment.setData("2208最棒");
                return true;//不会触发点击事件
            }
        });
        replaceFrag(new TwoFragment());
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb1:
                        replaceFrag(new TwoFragment());
                        break;
                    case R.id.rb2:
                        replaceFrag(new ThreeFragment());
                        break;
                }
            }
        });

        return view;
    }

    private void replaceFrag(Fragment fragment) {
        getChildFragmentManager().beginTransaction().replace(R.id.frame_one,fragment).commit();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.d("sss", "onCreate: 被创建");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        Log.d("sss", "onDestroy: 被销毁");
        super.onDestroy();
    }

    private void initView(View view) {
        tv = (TextView) view.findViewById(R.id.tv);
        rg = (RadioGroup) view.findViewById(R.id.rg);
    }
}